package com.deng.leaf.core.service;

import com.alibaba.druid.pool.DruidDataSource;
import com.deng.leaf.core.IDGen;
import com.deng.leaf.core.common.Result;
import com.deng.leaf.core.exception.InitException;
import com.deng.leaf.core.segment.dao.IDAllocDao;
import com.deng.leaf.core.segment.dao.impl.IDAllocDaoImpl;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

@Component
public class SegmentService {
    private Logger logger = LoggerFactory.getLogger(SegmentService.class);

    @Autowired
    private IDGen segmentIDGenImpl;
    private DruidDataSource dataSource;

//    public SegmentService(){
//
//    }

//    public SegmentService(String url, String username, String pwd) throws SQLException, InitException {
//        Preconditions.checkNotNull(url,"database url can not be null");
//        Preconditions.checkNotNull(username,"username can not be null");
//        Preconditions.checkNotNull(pwd,"password can not be null");
//        // Config dataSource
//        dataSource = new DruidDataSource();
//        dataSource.setUrl(url);
//        dataSource.setUsername(username);
//        dataSource.setPassword(pwd);
//        dataSource.init();
//        // Config Dao
//        IDAllocDao dao = new IDAllocDaoImpl(dataSource);
//        // Config ID Gen
//        idGen = new SegmentIDGenImpl();
//        ((SegmentIDGenImpl) idGen).setDao(dao);
//        if (idGen.init()) {
//            logger.info("Segment Service Init Successfully");
//        } else {
//            throw new InitException("Segment Service Init Fail");
//        }
//    }

    public Result getId(String key) {
        return segmentIDGenImpl.get(key);
    }

//    public SegmentIDGenImpl getIdGen() {
//        if (idGen instanceof SegmentIDGenImpl) {
//            return (SegmentIDGenImpl) idGen;
//        }
//        return null;
//    }

}
